package com.huaxi.ddgw.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.huaxi.ddgw.common.exception.GuiguException;
import com.huaxi.ddgw.feign.product.ProductFeignClient;
import com.huaxi.ddgw.model.dto.h5.UserLoginDto;
import com.huaxi.ddgw.model.dto.h5.UserRegisterDto;
import com.huaxi.ddgw.model.entity.user.UserBrowseHistory;
import com.huaxi.ddgw.model.entity.user.UserCollect;
import com.huaxi.ddgw.model.entity.user.UserInfo;
import com.huaxi.ddgw.model.vo.common.ResultCodeEnum;
import com.huaxi.ddgw.model.vo.h5.UserInfoVo;
import com.huaxi.ddgw.user.mapper.UserBrowseHistoryMapper;
import com.huaxi.ddgw.user.mapper.UserCollectMapper;
import com.huaxi.ddgw.user.mapper.UserInfoMapper;
import com.huaxi.ddgw.user.service.UserInfoService;
import com.huaxi.ddgw.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserCollectMapper userCollectMapper;

    @Autowired
    private UserBrowseHistoryMapper userBrowseHistoryMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    //注册
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //userRegisterDto获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();
        //验证码校验
        //从redis获取发送的验证码
        String redisCode = redisTemplate.opsForValue().get(username);
        //获取输入的验证码 进行比对
        if (!redisCode.equals(code)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //校验用户名username不能重复
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //封装添加数据 调用方法添加数据库
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");

        userInfoMapper.save(userInfo);
        //从redis删除发送的验证码
        redisTemplate.delete(username);
    }

    //登录
    @Override
    public String login(UserLoginDto userLoginDto) {
        //dto获取用户名密码
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        //根据用户名查询数据库 得到用户信息
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //比较密码是否一致
        String database_password = userInfo.getPassword();
        String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!database_password.equals(md5_password)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //校验用户是否禁用
        if (userInfo.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //把用户信息放到redis里面
        redisTemplate.opsForValue().set("user:spzx:" + token, JSON.toJSONString(userInfo), 30, TimeUnit.DAYS);
        //返回token
        return token;
    }

    //获取当前登录用户信息
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        //从redis根据token获取用户信息
        /*String userJson = redisTemplate.opsForValue().get("user:spzx:" + token);
        if (!StringUtils.hasText(userJson)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);*/
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        //userInfo -- VO
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    //保存商品浏览信息
    @Override
    public void saveUserCollect(Long skuId) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserBrowseHistory userBrowseHistory = new UserBrowseHistory();
        userBrowseHistory.setUserId(userInfo.getId());
        userBrowseHistory.setCreateTime(new Date());
        userBrowseHistory.setUpdateTime(new Date());
        userBrowseHistory.setSkuId(skuId);
        userBrowseHistory.setIsDeleted(0);
        userBrowseHistoryMapper.saveUserBrowseHistory(userBrowseHistory);
    }

    //商品浏览信息分页展示
    @Override
    public List<UserBrowseHistory> findUserBrowseHistoryPage(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        List<UserBrowseHistory> userBrowseHistoryList = userBrowseHistoryMapper.findUserBrowseHistoryPage(userInfo.getId());
        return userBrowseHistoryList;
    }

    //添加收藏
    @Override
    public void saveCollect(Long skuId) {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userInfo.getId());
        userCollect.setCreateTime(new Date());
        userCollect.setUpdateTime(new Date());
        userCollect.setSkuId(skuId);
        userCollect.setIsDeleted(0);
        userCollectMapper.saveCollect(userCollect);
    }

    //收藏商品分页展示
    @Override
    public List<UserCollect> findUserCollectPage(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        List<UserCollect> userCollectList = userCollectMapper.findUserCollectPage(userInfo.getId());
        return userCollectList;
    }


}
